package com.hk.service.impl;

import com.hk.commons.CacheConstants;
import com.hk.commons.EmailRes;
import com.hk.commons.HttpUtils;
import com.hk.commons.RedisCilent;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.commons.vo.Returnsms;
import com.hk.service.IMsg;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class MsgImpl implements IMsg {
    private Logger logger = LoggerFactory.getLogger(MsgImpl.class);

    @Value("${msg.host}")
    private String host;


    @Value("${msg.userid}")
    private String userid;

    @Value("${msg.account}")
    private String account;

    @Value("${msg.password}")
    private String password;

    @Value("${push.mail.url}")
    private String mail_url;






    private static Map<String, String> params = new HashMap<>();


    @PostConstruct
    public void init() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sf.format(System.currentTimeMillis());
        String originalString = this.account + this.password + timestamp;
        String sign = MD5Crypter.md5Encrypt(originalString);
        params.put("userid", this.userid);
        params.put("account", this.account);
        params.put("password", this.password);
        params.put("timestamp", timestamp);
        params.put("sign", sign);
        params.put("sendTime", "");
        params.put("action", "send");
        params.put("extno", "");
    }


    /**
     * 发送短息
     * @param mobile
     * @param content
     * @return
     */
    @Override
    public boolean sendMsg(String mobile, String content) {
        // 发送验证码
        StringBuffer buffer = new StringBuffer();
        buffer.append(content);
        try {
            params.put("content", new String(buffer.toString()
                    .getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        params.put("mobile", mobile);
        String result = "";
        boolean t = false;
        try {
            result = HttpUtils.invokePostForm(this.host, params, 5000);
            Returnsms sb = new Returnsms();
            sb = this.XMLStringToBean(result);
            logger.info("params:{}", params);
            logger.info("Send msg Result:{}", result);
            if (sb.getMessage().equals("ok")) {
                t = true;
            } else {
                logger.info("Send msg fail mobile:{} , Result:{}", mobile,
                        result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;

    }




    public Returnsms XMLStringToBean(String xmlStr) {
        Returnsms ben = new Returnsms();
        try {
            JAXBContext context = JAXBContext.newInstance(Returnsms.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            ben = (Returnsms) unmarshaller.unmarshal(new StringReader(xmlStr));
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return ben;
    }


    @Override
    public boolean sendMail(EmailRes res) {
        RestTemplate restTemplate = new RestTemplate();

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(res,
                    headers);

            Object result = restTemplate.postForEntity(mail_url, requestEntity, Object.class);

            logger.info("resturn result ={}", result);
////            if (!result.getBody()) {
////                logger.info("cancelOrder订单失败！orderId={}", order.getId());
////            } else {
////                returnVal = true;
////                logger.info("cancelOrder success orderId={}", order.getId());
//            }
        } catch (Exception e) {
            logger.error("发送验证邮件异常！", e);
        }

        return false;
    }


}
